import { AppDispatch } from './../index';
import {
  addUserChannelByIdAPI,
  delUserChannelListAPI,
  getChannelListAPI,
  getUserChannelListAPI,
} from '@/api/channel';
import { ChannelType } from '../redurce/channel';
import { getLocalChannels, hasToken, setLocalChannels } from '@/utils/storage';

export const getChannelListAction = () => {
  return async (dispatch: AppDispatch) => {
    const res = await getChannelListAPI();
    console.log('res  ----->  ', res);
    dispatch({ type: 'channel/saveAllList', payload: res.data.channels });
  };
};

export const getUserChannelListAction = () => {
  return async (dispatch: AppDispatch) => {
    const res = await getUserChannelListAPI();
    console.log('res  ----->  ', res);
    dispatch({ type: 'channel/saveUserList', payload: res.data.channels });
  };
};

export const delUserChannelListAction = (id: number) => {
  return async (dispatch: AppDispatch) => {
    const res = await delUserChannelListAPI(id);
    console.log('res  ----->  ', res);

    dispatch({ type: 'channel/delUserList', payload: id });
  };
};

export const addUserChannelListAction = (newChannel: ChannelType) => {
  return async (dispatch: AppDispatch) => {
    // 有token时
    if (hasToken()) {
      const res = await addUserChannelByIdAPI([newChannel]);
      console.log('res  ----->  ', res);
      dispatch({ type: 'channel/addUserList', payload: newChannel });
      return;
    }
    // 无token时,从缓存中取出关注的频道列表
    const localList = getLocalChannels();
    // 本地缓存中又保存的频道列表,直接存入redux中
    if (localList.length) {
      dispatch({ type: 'channel/saveUserList', payload: localList });
      return;
    }
    // 如果缓存中没有保存的频道列表,从全部的频道列表取出前十个
    const res = await getChannelListAPI();
    dispatch({
      type: 'channel/saveUserList',
      payload: res.data.channels.slice(0, 10),
    });
    setLocalChannels(res.data.channels.slice(0, 10));
  };
};

export const addCurrentIdAction = (id: number) => {
  return {
    type: 'channel/addCurrentId',
    payload: id,
  };
};
